﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace WPFConsole
{
    public partial class PConsole
    {
        void ConnectCommand()
        {
            string input = tbInput.Text;
            List<string> tokens = input.Split(' ').ToList();
            if (!_connected)
            {
                try
                {
                    _sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    IPEndPoint localEndPoint = new IPEndPoint(Dns.GetHostAddresses(tokens[1])[Dns.GetHostAddresses(tokens[1]).Length - 1], 1234);
                    _sck.Connect(localEndPoint);
                    _connected = true;
                    ClearInput();
                    _listener = new Thread(Listen);
                    _listener.Start();
                }
                catch (ArgumentOutOfRangeException)
                {
                    _connected = false;
                    WriteLine("Insufficient parameters. Usage: connect <IPAddress>");
                }
                catch (Exception e)
                {
                    _connected = false;
                    WriteLine("Error: " + e.Message + "\nSource: " + e.Source);
                }
            }
            else
            {
                WriteLine("Already connected to a server.");
            }
        }
        void HelpCommand()
        {
            string input = tbInput.Text;
            //List<string> tokens = input.Split(' ').ToList<string>();
            string commandList = _commands.Keys.Aggregate("", (current, command) => current + (command + '\t'));
            WriteLine("Available client commands: "+commandList.Trim());
            if (_connected)
            {
                SendToServer(input);
            }
            ClearInput();
        }

        void DisconnectCommand()
        {
            //string input = tbInput.Text;
            //List<string> tokens = input.Split(' ').ToList<string>();
            WriteLine("Will now disconnect from server...");
            _sck.Close();
            _connected = false;
            WriteLine("Socket closed. Successfully disconnected from server.");
            ClearInput();
        }

        void PingCommand()
        {
            if (!_connected) return;
            SendToServer("PING");
            SendToServer("PING");
            SendToServer("PING");
        }

        void ClearCommand()
        {
            
            if (tbConsole.Dispatcher.Thread == Thread.CurrentThread)
            {
                tbConsole.Document.Blocks.Clear();
            }
            else
            {
                tbConsole.Dispatcher.Invoke(new VoidMethod(ClearCommand));
            }
            ClearInput();
        }

    }
}
